package com.web.kdl.service.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web.kdl.common.result.CommonResult;
import com.web.kdl.daoV2.auth.RoleDao;
import com.web.kdl.daoV2.auth.RolePermissionDao;
import com.web.kdl.entity.auth.PermissionInfo;
import com.web.kdl.entity.auth.RoleInfo;
import com.web.kdl.entity.auth.RolePermission;
import com.web.kdl.pojo.form.RoleForm;
import com.web.kdl.pojo.form.RoleQueryForm;
import com.web.kdl.pojo.form.RoleUpdateForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author： shulibin
 * @Date： 2025/7/30 13:48
 * @Describe：
 */
@Service
public class RoleServiceImpl implements RoleService{
    @Resource
    RoleDao roleDao;

    @Resource
    RolePermissionDao rolePermissionDao;
    @Override
    public List<RoleInfo> listRoles() {
        List<RoleInfo> list = roleDao.selectList(null);
        return list;
    }

    @Override
    public RoleInfo getById(String id) {
        RoleInfo role = roleDao.selectById(id);
        return role;
    }

    @Override
    public List<String> getRolePermissions(String id) {
        return roleDao.findPermissionsByRoleId(id);
    }

    @Override
    @Transactional
    public CommonResult save(RoleForm form) {
        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setRoleName(form.getRoleName());
        roleInfo.setRoleCode(form.getRoleCode());
        roleInfo.setDescription(form.getDescription());
        int res = roleDao.insert(roleInfo);
        if (form.getPermissionIds() != null) {
            List<RolePermission> rolePermissions = form.getPermissionIds().stream()
                    .map(permissionId -> new RolePermission(roleInfo.getId(), permissionId))
                    .collect(Collectors.toList());
            rolePermissionDao.insertBatch(rolePermissions);
        }
        return res>0?CommonResult.success("角色添加成功"):CommonResult.error("角色添加失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateById(RoleUpdateForm form) {
        RoleInfo roleInfo = roleDao.selectById(form.getId());
        if (roleInfo == null){
            return CommonResult.error("角色不存在");
        }
        roleInfo.setRoleCode(form.getRoleCode());
        roleInfo.setRoleName(form.getRoleName());
        if (form.getDescription() != null)
        roleInfo.setDescription(form.getDescription());
        // form.getPermissions()存放权限ID 那么就要往role_permission表里添加数据
        rolePermissionDao.delete(new QueryWrapper<RolePermission>().eq("role_id", roleInfo.getId()));
        if (form.getPermissionIds() != null && form.getPermissionIds().size() > 0) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (String permissionId : form.getPermissionIds()) {
                RolePermission rolePermission = new RolePermission(roleInfo.getId(), permissionId);
                rolePermissions.add(rolePermission);
            }
            rolePermissionDao.insertBatch(rolePermissions);
        }
        int res = roleDao.updateById(roleInfo);
        return res>0?CommonResult.success("角色更新成功"):CommonResult.error("角色更新失败");
    }

    @Override
    @Transactional
    public CommonResult removeById(String id) {
        rolePermissionDao.delete(new QueryWrapper<RolePermission>().lambda().eq(RolePermission::getRoleId, id));
        int res = roleDao.deleteById(id);
        return res>0?CommonResult.success("角色删除成功"):CommonResult.error("角色删除失败");
    }

    @Override
    @Transactional
    public CommonResult assignPermissions(String id, List<String> permissionIds) {
        // 删除原有权限
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getRoleId, id);
        rolePermissionDao.delete(wrapper);

        // 添加新权限
        List<RolePermission> list = permissionIds.stream()
                .map(permId -> new RolePermission(id, permId))
                .collect(Collectors.toList());
        int i = rolePermissionDao.insertBatch(list);
        return i > 0?CommonResult.success("分配成功"):CommonResult.error("分配失败");
    }

    @Override
    public Page<RoleInfo> pageRoles(RoleQueryForm queryForm) {
        Page<RoleInfo> page = new Page<>(queryForm.getPageNum(), queryForm.getPageSize());
        LambdaQueryWrapper<RoleInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(queryForm.getRoleName())){
            queryWrapper.like(RoleInfo::getRoleName, queryForm.getRoleName());
        }
        // 执行分页查询
        Page<RoleInfo> rolePage = roleDao.selectPage(page, queryWrapper);
        return rolePage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult removeBatchByIds(List<String> ids) {
        rolePermissionDao.delete(new QueryWrapper<RolePermission>().lambda().in(RolePermission::getRoleId, ids));
        int i = roleDao.deleteBatchIds(ids);
        if (i ==ids.size()){
            return CommonResult.success("批量删除成功");
        }
        return CommonResult.error(ids.size()-i+"条删除失败");
    }

    /**
     * 移除角色的某个权限
     * @param roleId 角色ID
     * @param permissionId 权限ID
     * @return 移除结果
     */
    @Override
    public CommonResult removePermission(String roleId, String permissionId) {
        int delete = rolePermissionDao.delete(new QueryWrapper<RolePermission>().lambda()
                .eq(RolePermission::getRoleId, roleId)
                .eq(RolePermission::getPermissionId, permissionId));
        return delete > 0?CommonResult.success("移除成功"):CommonResult.error("移除失败");
    }
}
